<template>
  <section class="section-task-details" v-loading="loading">
    <header class="section-task-header">
      <div class="task-form-item">
        <el-button type="primary" @click="handleCreateAd">立即提交审核</el-button>
      </div>
      <div class="task-form-item">
        <el-button type="primary" @click="handleCancelSubmitTask(Array.from(multipleSelection))">批量取消定时</el-button>
      </div>
      <div class="task-form-item">
        <el-button type="primary" @click="handleCheckTaskStatus">查看审核状态</el-button>
      </div>
      <!--      <div class="task-form-item">-->
      <!--        <el-checkbox>勾选所有媒体账号的全部广告计划</el-checkbox>-->
      <!--      </div>-->
      <!--      <div class="task-form-item">所有账号广告组数量：<span class="primary-text">10</span></div>-->
      <!--      <div class="task-form-item">定时任务数：<span class="primary-text">100</span></div>-->
      <!--      <div class="task-form-item">提交成功：<span class="success-text">30</span></div>-->
    </header>

    <section class="section-task-body">
      <div class="task-detail-header">
        <div class="task-form-item">
          <el-checkbox
            v-model="taskDetails.checked"
            :indeterminate="taskDetails.indeterminate"
            :disabled="taskDetails.disabled"
          >勾选此账户的全部广告计划</el-checkbox>
        </div>
        <div class="task-form-item">{{ taskDetails.advertiser_alias ? taskDetails.advertiser_alias : taskDetails.advertiser_id }}</div>
        <div class="task-form-item">广告组数量：<span class="primary-text">{{ taskDetails.campaignList.length }}</span></div>
        <div class="task-form-item">广告计划数量：<span class="primary-text">{{ taskDetails.ad_length }}</span></div>
        <div class="task-form-item">定时任务数：<span class="primary-text">{{ taskDetails.task_length }}</span></div>
        <div class="task-form-item">提交成功：<span class="success-text">{{ taskDetails.success_length }}</span></div>
        <div class="task-form-item">提交失败：<span class="error-text">{{ taskDetails.failed_length }}</span></div>
      </div>

      <div class="task-detail-body">
        <el-scrollbar view-class="outer-scrollbar-view" height="100%">
          <div class="task-detail-scrollbar">
            <!-- 表头 -->
            <div class="task-table-header">
              <el-table border height="100%">
                <el-table-column label="广告组">
                  <el-table-column label="选择" width="60" align="center">
                    <template #default>
                      <el-checkbox></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column label="广告组信息" min-width="160"></el-table-column>
                </el-table-column>
                <el-table-column label="状态与操作">
                  <el-table-column label="选择" width="60" align="center"></el-table-column>
                  <el-table-column label="提交状态" min-width="126"></el-table-column>
                  <el-table-column label="操作" min-width="80"></el-table-column>
                </el-table-column>
                <el-table-column label="广告计划">
                  <el-table-column label="计划名称" min-width="240"></el-table-column>
                  <el-table-column label="预算" min-width="130"></el-table-column>
                  <el-table-column label="目标转化出价" min-width="130"></el-table-column>
                </el-table-column>
                <el-table-column label="广告内容">
                  <el-table-column label="用户定向" min-width="210">
                    <template #header>
                      <template v-if="taskDetails.original_strategy === 'target'">用户定向（<span class="primary-text">按用户定向分组</span>）</template>
                      <template v-else>用户定向</template>
                    </template>
                  </el-table-column>

                  <el-table-column label="创意素材" min-width="210">
                    <template #header>
                      <template v-if="taskDetails.original_strategy === 'material'">创意素材（<span class="primary-text">按创意素材分组</span>）</template>
                      <template v-else>创意素材</template>
                    </template>
                  </el-table-column>

                  <el-table-column label="落地页" min-width="210">
                    <template #header>
                      <template v-if="taskDetails.original_strategy === 'landing_page'">落地页（<span class="primary-text">按落地页分组</span>）</template>
                      <template v-else>落地页</template>
                    </template>
                  </el-table-column>

                  <el-table-column label="标题包" min-width="210">
                    <template #header>
                      <template v-if="taskDetails.original_strategy === 'title'">标题包（<span class="primary-text">按标题包分组</span>）</template>
                      <template v-else>标题包</template>
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </div>
            <!-- /表头 -->

            <div class="task-table-body" @click="handleClick($event)">
              <el-scrollbar height="100%">
                <el-table
                  v-for="(campaign, campaignIndex) in taskDetails.campaignList"
                  :key="campaign.campaign_index"
                  :data="campaign.adAndCreativityList"
                  :show-header="false"
                  tooltip-effect="light"
                  border
                  :span-method="params => spanMethod(params, campaign.adAndCreativityList.length)"
                >
                  <el-table-column label="选择" width="60" align="center">
                    <template #default>
                      {{campaign.adAndCreativityList.length}}
                      <el-checkbox
                        v-model="campaign.checked"
                        :disabled="campaign.disabled"
                        :indeterminate="campaign.adAndCreativityList.filter(item => item.checked).length > 0
                    && campaign.adAndCreativityList.filter(item => item.checked).length < campaign.adAndCreativityList.length"
                        :name="`${campaign.campaign_index}_${campaignIndex}`"
                      ></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column label="广告组信息" min-width="160">
                    <template #default>
                      <div class="campaign-name">
                        <div class="strong-text">广告组名称：</div>
                        <div>{{ campaign.campaign_name }}</div>
                      </div>
                      <div class="campaign-name">
                        <div class="strong-text">推广目标：</div>
                        <div>
                          {{ TT_LANDING_TYPES.find(item => item.value === campaign.marketing_purpose).label }}_{{ TT_LANDING_TYPES.find(item => item.value === campaign.marketing_purpose).children.find(item => item.value === campaign.landing_type).label }}_{{ campaign.adAndCreativityList[0]?.app_name }}
                        </div>
                      </div>
                      <div class="campaign-name">
                        <div class="strong-text">预算：</div>
                        <div>{{ campaign.budget_mode === 'BUDGET_MODE_INFINITE' ? '不限' : campaign.budget }}</div>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column label="选择" width="60" align="center">
                    <template #default="{row, $index}">
                      <el-checkbox
                        v-model="row.checked"
                        :disabled="row.disabled"
                        :name="`${campaign.campaign_index}_${campaignIndex}_${row.ad_index}_${$index}`"
                      ></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column label="提交状态" min-width="126">
                    <template #default="{row}">
                      <template v-if="row.submit_status === '定时提交'">
                        <span class="warning-text">{{ taskDetails.task_submit_time }}<br>定时提交</span>
                      </template>
                      <template v-else-if="row.submit_status === '待提交'">
                        <span>待提交</span>
                      </template>
                      <template v-else-if="row.submit_status === '已提交'">
                        <span class="primary-text">已提交</span>
                      </template>
                      <template v-else-if="row.submit_status === '成功'">
                        <span class="success-text">成功</span>
                      </template>
                      <template v-else>
                        <el-tooltip
                          :content="row.fail_reason"
                          effect="light"
                          placement="right"
                        >
                          <span class="error-text">{{ row.submit_status }}</span>
                        </el-tooltip>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" min-width="80">
                    <template #default="{row, $index}">
                      <template v-if="row.submit_status === '定时提交'">
                        <el-tooltip
                          effect="light"
                          content="取消提交后不能再恢复定时任务"
                          placement="top"
                        >
                          <el-button type="text" :disabled="row.disabled">
                            <span
                              data-type="cancel"
                              :data-index="`${campaign.campaign_index}_${campaignIndex}_${row.ad_index}_${$index}`"
                              :data-disabled="row.disabled"
                            >取消定时</span>
                          </el-button>
                        </el-tooltip>
                      </template>

                      <template v-else-if="row.submit_status === '待提交'">
                        <el-button type="text" :disabled="row.disabled">
                          <span
                            data-type="delete"
                            :data-index="`${campaign.campaign_index}_${campaignIndex}_${row.ad_index}_${$index}`"
                            :data-disabled="row.disabled"
                          >删除</span>
                        </el-button>
                      </template>

                      <template v-else>
                        <el-button type="text" :disabled="true">删除</el-button>
                      </template>
                    </template>
                  </el-table-column>

                  <el-table-column label="计划名称" prop="ad_name" min-width="240"></el-table-column>
                  <el-table-column label="预算" prop="budget" min-width="130">
                    <template #default="{row}">{{ row.budget_mode === 'BUDGET_MODE_DAY' ? '日预算' : '总预算' }}：{{ row.budget }}</template>
                  </el-table-column>
                  <el-table-column label="目标转化出价" prop="cpa_bid" min-width="130">
                    <template #default="{row}">{{ row.adjust_cpa === 1 ? row.pricing.includes('PRICING_O') ? row.cpa_bid : row.bid : '自动出价' }}</template>
                  </el-table-column>

                  <el-table-column label="用户定向" prop="original_target" min-width="210">
                    <template #default="{row}">
                      <el-row justify="space-between" align="middle" :gutter="10">
                        <el-col :span="18">{{ row.original_target.name }}</el-col>

                        <el-col :span="6">
                          <target-detail :data="row.original_target" placement="left" :append-to-body="true">
                            <el-button type="text">查看</el-button>
                          </target-detail>
                        </el-col>
                      </el-row>
                    </template>
                  </el-table-column>

                  <el-table-column label="创意素材" prop="original_material" min-width="210">
                    <template #default="{row}">
                      <el-row justify="space-between" align="middle" :gutter="10">
                        <el-col :span="18">{{ row.original_material.group_name }}</el-col>

                        <el-col :span="6">
                          <el-button type="text" @click="materialPreviewRef.open([...row.original_material.video_list, ...row.original_material.image_list])">查看</el-button>
                        </el-col>
                      </el-row>
                    </template>
                  </el-table-column>

                  <el-table-column label="落地页" prop="original_landing_page" min-width="210">
                    <template #default="{row}">
                      <el-row v-if="row.original_landing_page" justify="space-between" align="middle" :gutter="10">
                        <el-col :span="18">
                          <div class="multi-ellipsis--l2">
                            <span v-if="row.original_landing_page.site_id">
                              <el-tooltip
                                :append-to-body="false"
                                effect="light"
                                placement="left"
                              >
                                <template #content>
                                  <div style="text-align: left;">使用橙子建站的落地页创建的广告计划不支持分包提交</div>
                                </template>
                                <span class="warning-text">橙子建站</span>
                              </el-tooltip>
                            </span>{{row.original_landing_page.name || row.original_landing_page.name_alias}}
                          </div>
                        </el-col>

                        <el-col :span="6">
                          <el-button type="text" @click="landingPagePreviewRef.show({
                          url: row.original_landing_page.thumbnail,
                          name: row.original_landing_page.name || row.original_landing_page.name_alias,
                        })">预览</el-button>
                        </el-col>
                      </el-row>
                      <div class="txt-center" v-else>无</div>
                    </template>
                  </el-table-column>

                  <el-table-column label="标题包（按标题包分组）" prop="original_title" min-width="210">
                    <template #default="{row}">
                      <el-row justify="space-between" align="middle" :gutter="10">
                        <el-col :span="18">
                          <div class="multi-ellipsis--l2">{{ row.original_title.group_name }}</div>
                        </el-col>

                        <el-col :span="6">
                          <el-tooltip
                            effect="light"
                            placement="left"
                          >
                            <template #content>
                              <ul class="table-title-list">
                                <li v-for="(item, index) in row.original_title.list" :key="index">{{ item }}</li>
                              </ul>
                            </template>
                            <el-button type="text">查看</el-button>
                          </el-tooltip>
                        </el-col>
                      </el-row>
                    </template>
                  </el-table-column>
                </el-table>
              </el-scrollbar>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </section>
  </section>

  <!-- 落地页预览 -->
  <landing-page-preview ref="landingPagePreviewRef"></landing-page-preview>
  <!-- 创意素材预览 -->
  <material-preview ref="materialPreviewRef"></material-preview>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
} from 'vue';

import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定向包预览组件
import TargetDetail from '../Task1/components/targetDetail'
// 落地页预览组件
import LandingPagePreview from '../Task1/components/landingPagePreview';
// 创意素材预览组件
import MaterialPreview from '../Task1/components/materialPreview';

// import LandingPagePreview from '@/components/landingPagePreview'; // 落地页预览组件
// import MaterialPreview from '../programmed/component/materialPreview'; // 创意素材预览组件
// import TargetDetail from '../programmed/component/targetDetail'; // 定向包预览组件

import {
  getTaskDetails,
  cancelSubmitTask,
  delSubmitTask,
  checkTaskStatus,
  programmaticCreateAd,
} from './programmed';
import { TT_LANDING_TYPES } from './TT_LANDING_TYPES';

export default defineComponent({
  name: 'AdTaskDetails',
  components: {
    LandingPagePreview,
    MaterialPreview,
    TargetDetail,
  },
  /*beforeRouteEnter(to, from, next) {
    to.query.id === undefined ? next(from.path === '/login' ? '/' : from) : next();
  },*/
  setup() {
    const task_id = 123123;
    const state = reactive({
      loading: false,
      taskDetails: {
        checked: computed({
          get() {
            const checkedList = state.taskDetails.campaignList.filter(item => item.checked);
            return checkedList.length > 0 && checkedList.length === state.taskDetails.campaignList.length;
          },
          set(v) {
            state.multipleSelection.clear();
            state.taskDetails.campaignList.forEach((campaign, campaignIndex) => {
              if (!campaign.disabled) {
                campaign.checked = v;
                campaign.adAndCreativityList.forEach((ad, adIndex) => {
                  if (!ad.disabled) {
                    ad.checked = v;

                    if (v) state.multipleSelection.add(`${campaign.campaign_index}_${campaignIndex}_${ad.ad_index}_${adIndex}`);
                  }
                });
              }
            });
          },
        }),
        indeterminate: computed(() => {
          const checkedList = state.taskDetails.campaignList.filter(item => item.checked);
          return checkedList.length > 0 && checkedList.length < state.taskDetails.campaignList.length;
        }),
        disabled: computed(() => state.taskDetails.campaignList.filter(item => item.disabled).length === state.taskDetails.campaignList.length),
        ad_length: 0,
        task_length: 0,
        success_length: 0,
        failed_length: 0,
        campaignList: [],
      },
      multipleSelection: new Set(), // 选中的广告计划下标
      landingPagePreviewRef: null, // 落地页预览组件
      materialPreviewRef: null, // 创意素材预览组件
    });
    const adMap = new Map();

    // 获取定时任务详情数据
    getTaskDetails({
      task_id,
    }).then(({ data }) => {
      if (data.campaignList) {
        data.ad_length = 0;
        data.task_length = 0;
        data.success_length = 0;
        data.failed_length = 0;
        data.campaignList.forEach(campaign => {
          campaign.checked = false;
          campaign.adAndCreativityList.forEach(ad => {
            ad.checked = false;
            ad.disabled = false;
            data.ad_length++;

            if (ad.submit_status === '定时提交') {
              data.task_length++;
            } else if (ad.submit_status === '成功') {
              data.success_length++;
              ad.disabled = true;
            } else if (ad.submit_status === '失败') {
              data.failed_length++;
              ad.disabled = true;
            }
          });
          campaign.disabled = campaign.adAndCreativityList.filter(item => item.disabled).length === campaign.adAndCreativityList.length;
        });
        data.disabled = data.campaignList.filter(item => item.disabled).length === data.campaignList.length;
        state.taskDetails = {...state.taskDetails,...data}
        // Object.assign(state.taskDetails, data);

        state.taskDetails.campaignList.forEach(campaign => {
          campaign.adAndCreativityList.forEach(ad => {
            adMap.set(`${campaign.campaign_index}_${ad.ad_index}`, ad);
          });
        });
      } else {
        state.taskDetails.disabled = true;
      }
    }).finally(() => {
      state.loading = false;
    });

    // 合并单元格
    const spanMethod = ({ row, column, rowIndex, columnIndex }, adLength) => {
      const columnIndexList = [0, 1];

      switch (state.taskDetails.original_strategy) {
      case 'target':
        columnIndexList.push(8);
        break;
      case 'material':
        columnIndexList.push(9);
        break;
      case 'landing_page':
        columnIndexList.push(10);
        break;
      case 'title':
        columnIndexList.push(11);
      }

      if (columnIndexList.includes(columnIndex)) {
        if (rowIndex === 0) {
          return {
            rowspan: adLength,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    };

    // 事件委托
    const handleClick = e => {
      const [name, type, disabled, index] = [
        e.target.name, // checkbox 的 name 属性获取广告组及广告计划的下标，格式：广告组固定下标_广告计划固定下标_广告组的数组下标_广告计划的数组下标
        e.target.dataset.type, // 操作类型（取消定时任务：cancel、删除广告计划：delete）
        e.target.dataset.disabled, // 该广告组或广告计划是否可操作
        e.target.dataset.index, // 非 checkbox 获取广告组及广告计划的下标
      ];

      // 更新 checkbox 状态
      if (name && !e.target.disabled) {
        const idxArr = name.split('_');
        const campaignList = state.taskDetails.campaignList; // 广告组列表
        const campaign = campaignList[idxArr[1]];

        // 广告组
        if (idxArr.length === 2) {
          const campaignChecked = campaign.checked;
          const adAndCreativityList = campaign.adAndCreativityList;

          if (campaignChecked) {
            adAndCreativityList.forEach((ad, adIndex) => {
              if (!ad.disabled) {
                ad.checked = !campaignChecked;
                state.multipleSelection.delete(`${name}_${ad.ad_index}_${adIndex}`);
              }
            });
          } else {
            adAndCreativityList.forEach((ad, adIndex) => {
              if (!ad.disabled) {
                ad.checked = !campaignChecked;
                state.multipleSelection.add(`${name}_${ad.ad_index}_${adIndex}`);
              }
            });
          }
          return;
        }

        // 广告计划
        if (idxArr.length === 4) {
          const adAndCreativityList = campaign.adAndCreativityList;
          const adChecked = adAndCreativityList[idxArr[3]].checked;

          if (adChecked) {
            campaign.checked = !adChecked;
            state.multipleSelection.delete(`${name}`);
          } else {
            campaign.checked = adAndCreativityList.filter(item => item.checked).length + 1 === adAndCreativityList.length;
            state.multipleSelection.add(`${name}`);
          }

          return;
        }
      }

      if (disabled === 'false' && index) {
        const idxArr = index.split('_');

        // 取消定时任务
        if (type === 'cancel') {
          handleCancelSubmitTask([index]);
          return;
        }

        // 删除广告计划
        if (type === 'delete') {
          handleDelSubmitTask(index);
        }
      }
    };

    // 取消已提交的定时任务
    const handleCancelSubmitTask = idxArr => {
      const index_list = [];
      idxArr.forEach(idx => {
        const _idxArr = idx.split('_');
        const ad = state.taskDetails.campaignList[_idxArr[1]].adAndCreativityList[_idxArr[3]];

        if (ad.submit_status === '定时提交') {
          index_list.push({
            campaign_index: _idxArr[0],
            ad_index: _idxArr[2],
          });
        }
      });

      if (index_list.length === 0) {
        ElMessage.warning('请选择定时任务');
        return;
      }

      if (Date.now() >= (new Date(state.taskDetails.task_submit_time)).getTime()) {
        ElMessageBox.confirm(
          '已过定时时间，不能取消提交',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          handleCheckTaskStatus();
        }).catch(() => {});

        return;
      }

      ElMessageBox.confirm(
        `该操作不可恢复，确定${idxArr.length === 1 ? '取消该' : '批量取消'}定时任务吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        state.loading = true;
        cancelSubmitTask({
          index_list,
          task_id,
        }).then(({message}) => {
          ElMessage.success(message);

          idxArr.forEach(idx => {
            const _idxArr = idx.split('_');
            const campaign = state.taskDetails.campaignList[_idxArr[1]];
            const ad = campaign.adAndCreativityList[_idxArr[3]];

            ad.submit_status = '待提交';
            ad.checked = false;
            campaign.checked = false;
          });

          state.taskDetails.task_length -= index_list.length;
          state.multipleSelection.clear(); // 清空已选的广告计划
        });
      }).catch(() => {}).finally(() => {
        state.loading = false;
      });
    };

    // 删除定时任务
    const handleDelSubmitTask = index => {
      const idxArr = index.split('_');

      state.loading = true;
      delSubmitTask({
        campaign_index: idxArr[0],
        ad_index: idxArr[2],
        task_id,
      }).then(({message}) => {
        ElMessage.success(message);

        const campaign = state.taskDetails.campaignList[idxArr[1]];

        campaign.adAndCreativityList.splice(idxArr[3], 1);
        state.taskDetails.ad_length--;
        state.multipleSelection.delete(index);

        if (campaign.adAndCreativityList.length === 0) {
          state.taskDetails.campaignList.splice(idxArr[1], 1);
        }
      }).finally(() => {
        state.loading = false;
      });
    };

    // 批量提交广告计划审核
    const handleCreateAd = () => {
      if (state.multipleSelection.size === 0) {
        ElMessage.warning('请选择广告计划');
        return;
      }

      const data = {};
      const campaignListMap = new Map();

      Object.keys(state.taskDetails).forEach(key => {
        if (['advertiser_id', 'batch_id', 'is_user_extend_package'].includes(key)) data[key] = state.taskDetails[key];
      });

      state.multipleSelection.forEach(idx => {
        const idxArr = idx.split('_');
        const ad = state.taskDetails.campaignList[idxArr[1]].adAndCreativityList[idxArr[3]];

        if (ad.submit_status === '待提交' || (ad.submit_status === '定时提交' && Date.now() < (new Date(state.taskDetails.task_submit_time)).getTime())) {
          if (!campaignListMap.has(idxArr[0])) {
            const campaign = {
              adAndCreativityList: [],
            };
            Object.keys(state.taskDetails.campaignList[idxArr[1]]).forEach(key => {
              if (!['adAndCreativityList', 'checked', 'disabled'].includes(key)) campaign[key] = state.taskDetails.campaignList[idxArr[1]][key];
            });
            campaignListMap.set(idxArr[0], campaign);
          }

          const _ad = { ...ad };
          Reflect.deleteProperty(_ad, 'checked');
          Reflect.deleteProperty(_ad, 'disabled');
          Reflect.deleteProperty(_ad, 'submit_status');
          Reflect.deleteProperty(_ad, 'fail_reason');
          campaignListMap.get(idxArr[0]).adAndCreativityList.push(_ad);
        }
      });

      data.campaignList = Array.from(campaignListMap.values());

      if (data.campaignList.length > 0) {
        state.loading = true;
        programmaticCreateAd([data]).then(({data, message}) => {
          ElMessage.success(message);

          data.forEach(idx => {
            const idxArr = idx.split('_');
            let index = idxArr[1];
            const campaign = state.taskDetails.campaignList.find((item, campaignIndex) => {
              if (`${item.campaign_index}` === idxArr[1]) {
                index = `${index}_${campaignIndex}`;
                return true;
              }
              return false;
            });
            const ad = campaign.adAndCreativityList.find((item, adIndex) => {
              if (`${item.ad_index}` === idxArr[2]) {
                index = `${index}_${idxArr[2]}_${adIndex}`;
                return true;
              }
              return false;
            });

            ad.checked = false;
            ad.disabled = true;
            if (ad.submit_status === '定时提交') state.taskDetails.task_length--;
            ad.submit_status = '已提交';
            campaign.checked = false;
            campaign.disabled = campaign.adAndCreativityList.filter(item => item.disabled).length === campaign.adAndCreativityList.length;
            state.multipleSelection.delete(index);
          });
        }).finally(() => {
          state.loading = false;
          handleCheckTaskStatus();
        });
      } else {
        handleCheckTaskStatus();
      }
    };

    // 查看任务审核状态
    const handleCheckTaskStatus = () => {
      state.loading = true;
      checkTaskStatus({
        task_id,
      }).then(({data}) => {
        let success_length = 0;
        let failed_length = 0;

        data.forEach(item => {
          const ad = adMap.get(`${item.campaign_index}_${item.ad_index}`);

          ad.submit_status = item.submit_status;
          ad.fail_reason = item.fail_reason;

          if (item.submit_status === '成功') {
            success_length++;
            ad.checked = false;
            ad.disabled = true;
          } else if (item.submit_status === '失败') {
            failed_length++;
            ad.checked = false;
            ad.disabled = true;
          } else if (item.submit_status === '已提交') {
            ad.checked = false;
            ad.disabled = true;
          } else { // 其他情况（如：待提交）
            ad.checked = false;
            ad.disabled = false;
          }
        });

        state.taskDetails.campaignList.forEach(campaign => {
          campaign.checked = campaign.adAndCreativityList.filter(ad => ad.checked).length === campaign.adAndCreativityList.length;
          campaign.disabled = campaign.adAndCreativityList.filter(ad => ad.disabled).length === campaign.adAndCreativityList.length;
        });

        state.taskDetails.success_length = success_length;
        state.taskDetails.failed_length = failed_length;
      }).finally(() => {
        state.loading = false;
      });
    };

    return {
      ...toRefs(state),
      TT_LANDING_TYPES,
      spanMethod,
      handleClick,
      handleCancelSubmitTask,
      handleDelSubmitTask,
      handleCheckTaskStatus,
      handleCreateAd,
    };
  },
});
</script>

<style scoped lang="scss">
.table-title-list {
  max-width: 300px;

  > li + li { margin-top: .5em; }
}

.section-task-details {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 10px 10px;
  width: 100%;
  height: 100%;
  @include pageSection();
  font-size: 14px;

  > .section-task-header {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    padding-top: 20px;
    padding-bottom: 20px;
    color: $h1-text-color;

    > .task-form-item {
      & + .task-form-item { margin-left: 20px; }
      :deep(.el-checkbox__label) { color: $h1-text-color; }
    }
  }

  > .section-task-body {
    position: relative;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-top: 1px solid $border-color-base;
    border-left: 1px solid $border-color-base;
    //box-shadow: 0 0 0 1px $border-color-base inset;

    &:before {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      z-index: 99;
      display: block;
      width: 1px;
      height: 100%;
      background-color: $border-color-base;
      content: "";
    }

    &:after {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 99;
      display: block;
      width: 100%;
      height: 1px;
      background-color: $border-color-base;
      content: "";
    }

    > .task-detail-header {
      flex-shrink: 0;
      display: flex;
      padding: 15px 20px;
      color: $h1-text-color;

      > .task-form-item {
        & + .task-form-item { margin-left: 20px; }
        :deep(.el-checkbox__label) { color: $h1-text-color; }
      }
    }

    > .task-detail-body {
      flex-grow: 1;
      flex-direction: column;
      overflow: hidden;

      :deep(.outer-scrollbar-view) {
        width: 100%;
        height: 100%;
      }

      .task-detail-scrollbar {
        display: flex;
        flex-direction: column;
        width: 1826px;
        height: 100%;

        :deep(.el-table) {
          &.el-table--border th,
          &.el-table--border td  {
            border-color: $border-color-base;
            border-right: 1px solid $border-color-base;
          }
          &.el-table--border th:last-child { border-right: none; }
          &.el-table--border td:last-child:not([rowspan="1"]) { border-right: none; }

          &.el-table--border td:first-child .cell,
          &.el-table--border th:first-child .cell,
          &.el-table__body tr td:first-child .cell { padding-left: 10px; }

          .el-table__body .cell { line-height: 1.3; }

          .is-group th {
            background: $color-white;
            text-align: center;
          }
        }

        .task-table-header {
          flex-shrink: 0;
          overflow: hidden;
          margin-right: -1px;

          :deep(.el-table__body-wrapper) { display: none; }
        }

        .task-table-body {
          flex-grow: 1;
          overflow: hidden;
          margin-right: -1px;

          .el-table {
            margin-top: -1px;

            .campaign-name {
              & + .campaign-name { margin-top: 1em; }
              .strong-text { margin-bottom: .25em; }
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.layout-header[name="PlatformToutiaoAdvertisingTaskDetails"] {
  > .layout-header-menu { display: none; }
}
</style>
